import Konva from "konva"
export default class KonvaJs {
    constructor(id, content) {
        this.content = content;
        this.id = id;
        this.boardCount = 0;     // 画板数量
        this.currentBoardIndex = 0; // 当前活动画板索引
        this.initialStageHeight = 0; // 初始舞台高度
        this.stage = null;
        this.layer = this.newLayer(); // 图层
        this.tr = this.newTransformer(); // 变换器
        this.group = this.newGroup({ x: 0, y: 0 }); // 主组
        this.boards = [];        // 画板数组
        this.boardWidth = 0; // 画板宽度
        this.boardHeight = 0; // 画板高度
        // this.onBoardChange = null; // 画板切换回调
        // this.onContentChange = null; // 内容变化回调
    }

    // 初始化舞台
    init() {
        const el = document.getElementById(this.content);
        console.log(el);

        if (!el) {
            console.error(`找不到ID为${this.id}的DOM元素`);
            return;
        }

        // 设置舞台
        const { clientHeight, clientWidth } = el;
        this.initialStageHeight = clientHeight; // 记录初始高度

        this.stage = this.newStage({
            container: this.id,
            width: clientWidth,
            height: clientHeight,
            draggable: false
        });

        this.layer.add(this.group);
        this.layer.add(this.tr);
        this.stage.add(this.layer);

        // 初始化第一个画板
        this.drawBoard(0);
    }

    // 绘制画板
    drawBoard(type) {
        console.log(type);

        if (!this.stage) return;
        if (type === 1) {
            this.boardWidth = 750;
            this.boardHeight = this.boardWidth * 9 / 16;
        } else if (type === 0) {
            this.boardHeight = 600;
            this.boardWidth = this.boardHeight * 9 / 16;
        }


        // 计算位置居中
        const x = this.stage.width() / 2 - this.boardWidth / 2;
        let y, sectionStart = 0;

        if (this.boardCount === 0) {
            // 第一个画布的位置
            y = this.stage.height() / 2 - this.boardHeight / 2;
        } else {
            // 画板数量加一
            this.boardCount++;
            // 计算方式：初始高度 * 画板数量
            const newStageHeight = this.initialStageHeight * this.boardCount;

            // 更新舞台高度
            this.stage.height(newStageHeight);
            // 计算画板位置
            sectionStart = this.initialStageHeight * (this.boardCount - 1);
            y = sectionStart + (this.initialStageHeight / 2) - (this.boardHeight / 2);
        }
        // 创建画板
        const board = this.newRect({
            x, y,
            width: this.boardWidth,
            height: this.boardHeight,
            fill: "#fff",
            stroke: '#ddd',
            strokeWidth: 2,
        });
        const boarddIndex = this.boardCount;
        const boradShapesGroup = this.newGroup({
            x, y,
            name: `borrd-${boarddIndex}-shapes-group`
        })

        // 更新画板数量和当前画板
        if (this.boardCount === 0) {
            this.boardCount++;
            this.currentBoardIndex = 0;
        } else {
            this.currentBoardIndex = this.boardCount - 1;
            this.scrollToNewBoard(sectionStart)
        }

        this.group.add(board);
        this.layer.add(boradShapesGroup); // 将画板添加到数组中
        // 更新手柄
        this.tr.nodes([]);
        this.layer.draw();
    }

    //滚动到画板位置
    scrollToNewBoard(yPosition) {
        const el = document.getElementById(this.content);
        if (!el) return;

        // 延迟100ms后滚动，避免滚动冲突
        setTimeout(() => {
            el.scrollTo({
                top: yPosition,
                // 动画效果
                behavior: 'smooth'
            })
        }, 100);

    }

    // 绘制图形
    drawShapes(type, position) {
        console.log(position);

        if (!this.stage) return;
        let shapes;
        const id = this.getUUID();
        if (type === 'rect') {
            // const rectShapes = this.stage.find('.rect')
            shapes = this.newRect({
                id: id,
                title: '矩形',
                name: 'rect',
                width: 200,
                height: 100,
                fill: '#00D2FF',
                stroke: '#cdcdcd',
                strokeWidth: 1,
                type: 'rect',
                draggable: true,
                create: true,
                scaleX: 1,
                scaleY: 1,
                opacity: 1,
            })
        }
        if (!shapes) return;
        shapes.position(position)
        this.group.add(shapes);
        return shapes

    }

    // 生成UUID
    getUUID() {
        // 获取当前时间
        let d = Date.now()
        // 如果浏览器支持performance.now()方法，则将当前时间加上performance.now()的返回值
        if (typeof performance !== 'undefined' && typeof performance.now === 'function') {
            d += performance.now()
        }
        // 返回一个UUID
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            // 生成一个随机数
            const r = (d + Math.random() * 16) % 16 | 0
            // 将当前时间除以16
            d = Math.floor(d / 16)
            // 如果c为x，则返回r，否则返回r与0x3按位与的结果与0x8按位或的结果
            return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16)
        })
    }


    // Konva基础对象创建方法
    newStage(data) { return new Konva.Stage(data); }
    newLayer(data) { return new Konva.Layer(data); }
    newTransformer(data) { return new Konva.Transformer(data); }
    newGroup(data) { return new Konva.Group(data); }
    newRect(data) { return new Konva.Rect(data); }
    newCircle(data) { return new Konva.Circle(data); }
    newText(data) { return new Konva.Text(data); }
    newStar(data) { return new Konva.Star(data); }
    newRegularPolygon(data) { return new Konva.RegularPolygon(data); }
    newLine(data) { return new Konva.Line(data); }
    newArrow(data) { return new Konva.Arrow(data); }
    newImage(data) { return new Konva.Image(data); }
}